package cn.ecut.servlet;

import cn.ecut.model.Good;
import cn.ecut.model.User;
import cn.ecut.services.GoodServices;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@WebServlet("/lost/post")
public class PostLostServlet extends HttpServlet {

    private String goodname;
    private String goodtime;
    private String goodexplain;
    private String imgUrl;
    private User user;
    private static final String storeImgFileName = "lostImages";
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户
//        Object o = request.getSession().getAttribute("user");
        Object o = new User(1, "zhangsan", "qweasd", "123456", "男", "zhangsan@qq.com");
        if (o instanceof User) {
            user = (User) o;
        } else {
            // 此时证明没有登录
            request.setAttribute("msg","没有登录");
            request.getRequestDispatcher("/fail.jsp").forward(request, response);
        }

        //时间类型转换
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 'T' HH:mm");
        Date date = new Date();
        // 判断上传表单是否为multipart/form-data类型
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // 1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹
                // 2. 创建ServletFileUpload对象，并设置上传文件的大小限制。
                ServletFileUpload sfu = new ServletFileUpload(factory);
                sfu.setSizeMax(10 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte =
                // 1kb 1024kb=1M 1024M = 1G
                sfu.setHeaderEncoding("utf-8");
                // 3.调用ServletFileUpload.parseRequest方法解析request对象，得到一个保存了所有上传内容的List对象。
                @SuppressWarnings("unchecked")
                List<FileItem> fileItemList = sfu.parseRequest(request);
                Iterator<FileItem> fileItems = fileItemList.iterator();
                // 4. 遍历list，每迭代一个FileItem对象，调用其isFormField方法判断是否是上传文件
                while (fileItems.hasNext()) {
                    FileItem fileItem = fileItems.next();
                    // 普通表单元素
                    if (fileItem.isFormField()) {
                        String name = fileItem.getFieldName();// name属性值
                        String value = fileItem.getString("utf-8");// name对应的value值
//                        System.out.println(name + " = " + value);
                        if(name.equals("goodname"))
                            goodname=value;
                        else if (name.equals("goodtime")) {
                            goodtime = value;
                            date = df.parse(goodtime);
                        }
                        else if(name.equals("goodexplain"))
                            goodexplain=value;
                    }
                    // <input Type="file">的上传文件的元素
                    else {
                        String fileName = fileItem.getName();// 上传的文件名称
                        String suffix = fileName.substring(fileName.lastIndexOf('.'));//获取文件扩展名
                        // 新文件名（唯一）
                        String newFileName = new Date().getTime() + suffix;
                        // 5. 调用FileItem的write()方法，写入文件
                        //文件存储位置
                        ServletContext context = this.getServletContext();
                        // 获取绝对路径
                        String serverPath = context.getRealPath("") +"\\"+ storeImgFileName;
//                        System.out.println(serverPath);
                        // 如果存放头像的文件夹不存在则创建
                        File storeDir = new File(serverPath);
                        if (!storeDir.exists()) {
                            storeDir.mkdirs();
                        }
                        //将图片存入文件夹
                        File storeImage = new File(serverPath, newFileName);
                        // 将上传的文件写到服务器上指定的文件。
                        fileItem.write(storeImage);
                        // 6. 调用FileItem的delete()方法，删除临时文件
                        fileItem.delete();

                        //7:接下来就是把图片路径（headUrl）存储到自己的数据库中去了
                        imgUrl = storeImgFileName + "/" + newFileName; // 拼接相对路径 headImage/1478509873038.jpg
//                        System.out.println(imgUrl);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("请求格式错误");
        }
        //封装后存储到数据库
        Good good = new Good(goodname, new Timestamp(date.getTime()), goodexplain, imgUrl, user);
        GoodServices goodServices = new GoodServices();
        boolean result = goodServices.saveGood(good);
        if (result) {
            request.setAttribute("msg", "发布成功");
            response.sendRedirect("/mypost.jsp");
        } else {
            request.setAttribute("msg", "发布失败");
            response.sendRedirect("/mypost.jsp");
        }
    }
}
